package com.xyhy.starter.web.advice;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.xyhy.core.web.model.wrapper.Result;
import com.xyhy.core.web.model.wrapper.ResultCode;

import jakarta.servlet.http.HttpServletResponse;

@Slf4j
@RestControllerAdvice
public class SecurityExceptionAdvice extends ExceptionAdvice {

  @ExceptionHandler(value = BadCredentialsException.class)
  public Result<Object> badCredentialsExceptionHandler(BadCredentialsException ex, HttpServletResponse response) {
    log.error("exceptionHandler:BadCredentialsException", ex);
    return Result.fail(ResultCode.USER_PASSWORD_ERROR, new RuntimeException("账号或密码错误!"));
  }

  @ExceptionHandler(value = AuthenticationException.class)
  public Result<Object> authenticationExceptionHandler(AuthenticationException ex, HttpServletResponse response) {
    log.error("exceptionHandler:AuthenticationException", ex);
    return Result.fail(ResultCode.UN_AUTHORIZED, ex);
  }

  @ExceptionHandler(value = AccessDeniedException.class)
  public Result<Object> accessDeniedExceptionHandler(AccessDeniedException ex, HttpServletResponse response) {
    log.error("exceptionHandler:AccessDeniedException", ex);
    return Result.fail(ResultCode.FORBIDDEN, ex);
  }

  @ExceptionHandler(value = InternalAuthenticationServiceException.class)
  public Result<Object> internalAuthenticationServiceExceptionHandler(InternalAuthenticationServiceException ex,
                                                                      HttpServletResponse response) {
    log.error("exceptionHandler:InternalAuthenticationServiceException", ex);
    return Result.fail(ResultCode.USER_NOT_EXIST, ex);
  }

}
